function hideElement(id) {
	var element = document.getElementById(id);
	element.style.display = 'none';
}

function showElement(id) {
	var element = document.getElementById(id);
	element.style.display = 'block';
}

function showCreate() {
	hideElement("tableContent");
	var create = document.getElementById("create");
	if (!create.initialized) {
		var createBody = document.getElementById("createTableBody");
		for (var i = 0; i < 5; i++) {
			createColumn(createBody, createBody.childNodes.length + 1);
		}
		create.initialized = true;
	}
	showElement("create");
	syncer.component = {name: "create"};
}

function showTable(tableName) {
	hideElement("create");
	generateTableContent(tableName);
	showElement("tableContent");
	syncer.component = {name: "tableContent", tableName: tableName};
}

function hideAll() {
	hideElement("issues");
	hideElement("info");
	hideElement("tableList");
	hideElement("controlPanel");
	hideElement("gearsinfo");
	hideElement("installGearsLink");
}

/////////////////////////////////////////////////////////

function createTable() {
	var args = {};
	args.tableName = document.getElementById("tableName").value;
	args.ifNotExists = document.getElementById("createIfNotExists").checked;
	args.columns = [];
	var body = document.getElementById("createTableBody");
	var bodyChilds = body.childNodes;
	for (var i in bodyChilds) {
//		if (bodyChilds.hasOwnProperty(i) && typeof bodyChilds[i] !== "number") {
		if (Object.prototype.hasOwnProperty.call(bodyChilds, i) // IE hack :(
				&& typeof bodyChilds[i] !== "number") {
			var column = {};
			var trChilds = bodyChilds[i].childNodes;
			// 0 = label, 1 = name, 2 = type, 3 = pk, 4 = unique, 5 = null
			column.name = trChilds[1].childNodes[0].value;
			if (column.name.length == 0) continue;
			column.type = trChilds[2].childNodes[0].value;
			column.pk = trChilds[3].childNodes[0].childNodes[0].checked;
			column.unique = trChilds[4].childNodes[0].childNodes[0].checked;
			column.allowNull = trChilds[5].childNodes[0].childNodes[0].checked;
			args.columns.push(column);
		}
	}
	
//	console.debug(JSON.stringify(args));
	
	var result = data.createTable(args);
	if (result.success) {
		info.info("table " + args.tableName + " has been created locally.");
	} else {
		info.error(result.msg);
	}
	refreshTableList();
}

function insertIntoTable(tableName, fieldCount) {
	var values = [];
	// WARNING
	// warning this is special case for rowid as a first field !!!
	for (var i = 1; i < fieldCount; i++) { 
		var elementName = "__" + tableName + "_field" + i;
		var v = document.getElementById(elementName).value;
		if (!v) { v = null; }
		values.push(v);
	}
//	console.debug(values);
	var result = data.insertIntoTable(tableName, values);
	if (!result.success) {
		info.error(result.msg);
	}
	showTable(tableName);
}

function dropTable(tableName) {
	data.dropTable(tableName);
	refreshTableList();
}

function refreshTableList() {
	var tablelist = data.getTableList();
	var el = document.getElementById("tableListEntries");
//	console.debug(tablelist);
	var listStr = "";
	if (tablelist.length == 0) {
		listStr += "No tables";
	} else {
		for (var i in tablelist) {
			listStr += '<div class="tableborder"><div class="tablename">'
					+ '<a href="javascript: showTable(\'' + tablelist[i] + '\');">'
					+ tablelist[i] + '</a> <a href="javascript: dropTable(\''
					+ tablelist[i] + '\');" style="float: right;"><img src="images/delete.png" style="width: 20px; height: 20px; border-width: 0px;"></a></div>';
			listStr += '</div>';
		}
	}
	el.innerHTML = listStr;
}

function generateTableContent(tableName) {
	var content = data.getTableContent(tableName);
//	console.debug(JSON.stringify(content));
	var el = document.getElementById("tableContent");
	el.innerHTML = "";
	
	
	var contentTable = document.createElement("table");
	var header = document.createElement("tr");
//	header.className = "contentHeader";
	
	for (var i = 0; i < content.fieldCount; i++) {
		var headerField = document.createElement("td");
		headerField.className = "createInput";
		if (content.fields[i].hidden) {
			headerField.style.display = "none";
		}
		headerField.appendChild(document.createTextNode(content.fields[i].name));
		header.appendChild(headerField);
	}
	contentTable.appendChild(header);
	for (var j = 0; j < content.rows.length; j++) {
		var tableRow = document.createElement("tr");
		var row = content.rows[j];
		for (var l = 0; l < content.fieldCount; l++) {
			var field = document.createElement("td");
			if (content.fields[l].hidden) {
				field.style.display = "none";
				field.style.fontFamily = "monospace";
			}
			field.appendChild(document.createTextNode(row[l]));
			tableRow.appendChild(field);
		}
		
		// EDIT
		var editTd = document.createElement("td");
		var editLink = document.createElement("a");
		editLink.appendChild(document.createTextNode("edit"));
		editLink.addEventListener("click", function () {
			var childs = this.parentNode.parentNode.childNodes;
			for (var c in childs) {
				if (childs.hasOwnProperty(c) && typeof childs[c] === "object"){
					var child = childs[c];
					var fc = child.firstChild;
					if (fc.nodeType == 3) {
						var value = fc.textContent;
						child.removeChild(fc);
						var input = document.createElement("input");
						input.type = "text";
						input.value = value;
						child.appendChild(input);
					} else if (fc.nodeType === 1 && fc.firstChild.textContent === "edit") {
						child.style.display = "none";
					} else if (fc.nodeType === 1
							&& (fc.firstChild.textContent === "save" 
								|| fc.firstChild.textContent === "discard")) {
						child.style.display = "";
					}
				}
			}
		}, false);
		editTd.appendChild(editLink);
		
		// SAVE
		var saveTd = document.createElement("td");
		var saveLink = document.createElement("a");
		saveLink.rowindex = j;
		saveLink.appendChild(document.createTextNode("save"));
		saveLink.addEventListener("click", function () {
			var childs = this.parentNode.parentNode.childNodes;
			var values = [];
			for (var c in childs) {
				if (childs.hasOwnProperty(c) && typeof childs[c] === "object"){
					var child = childs[c];
					var fc = child.firstChild;
					if (fc.nodeName.toLowerCase() === "input") {
						var value = fc.value;
						if (!value) { value = null; }
						values.push(value);
						child.removeChild(fc);
						child.appendChild(document.createTextNode(value));
					} else if (fc.nodeName.toLowerCase() === "a" && fc.firstChild.textContent === "edit") {
						child.style.display = "";
					} else if (fc.nodeName.toLowerCase() === "a" 
							&& (fc.firstChild.textContent === "save" 
								|| fc.firstChild.textContent === "discard")) {
						child.style.display = "none";
					}
				}
			}
			var result = data.updateTable(tableName, values, content.fields);
			if (!result.success) {
				info.error(result.msg);
				var r = 0;
				for (var c2 in childs) {
					if (childs.hasOwnProperty(c2) && typeof childs[c2] === "object"){
						var child2 = childs[c2]; 
						var fc2 = child2.firstChild;
						if (fc2.nodeType == 3) {
							var value2 = content.rows[this.rowindex][r++];
							child2.removeChild(fc2);
							child2.appendChild(document.createTextNode(value2));
						}
					}
				}
			}
		}, false);
		saveTd.appendChild(saveLink);
		saveTd.style.display = "none";
		
		var discardTd = document.createElement("td");
		var discardLink = document.createElement("a");
		discardLink.appendChild(document.createTextNode("discard"));
		discardLink.rowindex = j;
		discardLink.addEventListener("click", function () {
			var childs = this.parentNode.parentNode.childNodes;
			var r = 0;
			for (var c in childs) {
				if (childs.hasOwnProperty(c) && typeof childs[c] === "object"){
					var child = childs[c];
					var fc = child.firstChild;
					if (fc.nodeName.toLowerCase() === "input") {
						var value = content.rows[this.rowindex][r++];
						child.removeChild(fc);
						child.appendChild(document.createTextNode(value));
					} else if (fc.nodeName.toLowerCase() === "a" && fc.firstChild.textContent === "edit") {
						child.style.display = "";
					} else if (fc.nodeName.toLowerCase() === "a" 
							&& (fc.firstChild.textContent === "save" 
								|| fc.firstChild.textContent === "discard")) {
						child.style.display = "none";
					}
				}
			}
		}, false);
		discardTd.appendChild(discardLink);
		discardTd.style.display = "none";
		
		// DELETE
		var deleteTd = document.createElement("td");
		var deleteLink = document.createElement("a");
		deleteLink.appendChild(document.createTextNode("delete"));
		deleteLink.rowid = row[0];
		deleteLink.addEventListener("click", function () {
			data.deleteFromTable(tableName, this.rowid);
		}, false);	
		deleteTd.appendChild(deleteLink);
		
		// TABLE ROW
		tableRow.appendChild(editTd);
		tableRow.appendChild(saveTd);
		tableRow.appendChild(discardTd);
		tableRow.appendChild(deleteTd);
		contentTable.appendChild(tableRow);
	}
	var insertRow = document.createElement("tr");
	for (var n = 0; n < content.fieldCount; n++) {
		var insertField = document.createElement("td");
		if (content.fields[n].hidden) {
			insertField.style.display = "none";
		}
		var insertInput = document.createElement("input");
		insertInput.type = "text";
		insertInput.id = "__" + tableName + "_field" + n;
		insertField.appendChild(insertInput);
		insertRow.appendChild(insertField);
	}
	var insertButton = document.createElement("input");
	insertButton.type = "button";
	insertButton.value = "insert";
	insertButton.addEventListener("click", function () {
		insertIntoTable(tableName, content.fieldCount);
	}, false);
	insertRow.appendChild(insertButton);
	contentTable.appendChild(insertRow);
	el.appendChild(contentTable);
}

function createColumn(parent, index, header) {
	// ROW
	var row = document.createElement("tr");
	
	// LABEL
	var columnLabelTd = document.createElement("td");
	var columnLabel = document.createTextNode("Column " + index + ": ");
	columnLabelTd.appendChild(columnLabel);
	
	// NAME
	var columnNameTd = document.createElement("td");
	var columnName = document.createElement("input");
	columnName.type = "text";
	columnName.className = "createInput";
	columnNameTd.appendChild(columnName);
	
	// TYPE
	var columnTypeTd = document.createElement("td");
	var columnType = document.createElement("select");
	var textOption = document.createElement("option");
	textOption.appendChild(document.createTextNode("TEXT"));
	var integerOption = document.createElement("option");
	integerOption.appendChild(document.createTextNode("INTEGER"));
	var realOption = document.createElement("option");
	realOption.appendChild(document.createTextNode("REAL"));
	var blobOption = document.createElement("option");
	blobOption.appendChild(document.createTextNode("BLOB"));
	columnType.appendChild(textOption);
	columnType.appendChild(integerOption);
	columnType.appendChild(realOption);
	columnType.appendChild(blobOption);
	columnTypeTd.appendChild(columnType);
	
	// PRIMARY KEY
	var columnPrimaryKeyTd = document.createElement("td");
	var columnPrimayKeyLabel = document.createElement("label");
	var columnPrimayKey = document.createElement("input");
	columnPrimayKey.type = "checkbox";
	columnPrimayKeyLabel.appendChild(columnPrimayKey);
	columnPrimayKeyLabel.appendChild(document.createTextNode("Yes"));
	columnPrimaryKeyTd.appendChild(columnPrimayKeyLabel);
	
	// UNIQUE
	var columnUniqueTd = document.createElement("td");
	var columnUniqueLabel = document.createElement("label");
	var columnUnique = document.createElement("input");
	columnUnique.type = "checkbox";
	columnUniqueLabel.appendChild(columnUnique);
	columnUniqueLabel.appendChild(document.createTextNode("Yes"));
	columnUniqueTd.appendChild(columnUniqueLabel);
	
	// NULL
	var columnNullTd = document.createElement("td");
	var columnNullLabel = document.createElement("label");
	var columnNull = document.createElement("input");
	columnNull.type = "checkbox";
	columnNullLabel.appendChild(columnNull);
	columnNullLabel.appendChild(document.createTextNode("Yes"));
	columnNullTd.appendChild(columnNullLabel);
	
	// ROW
	row.appendChild(columnLabelTd);
	row.appendChild(columnNameTd);
	row.appendChild(columnTypeTd);
	row.appendChild(columnPrimaryKeyTd);
	row.appendChild(columnUniqueTd);
	row.appendChild(columnNullTd);
	
	//PARENT
	parent.appendChild(row);
}